package com.ufun.financegateway.validation.annotation.validator;

import com.ufun.financegateway.validation.annotation.EnumValid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EnumValidator implements ConstraintValidator<EnumValid, String> {

    private Class<? extends Enum> enumClass;

    private boolean allowNull;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        this.enumClass = constraintAnnotation.enumClass();
        this.allowNull = constraintAnnotation.allowNull();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if (value == null) {
            return allowNull;
        }

        for (Enum element : enumClass.getEnumConstants()) {
            if (element.name().equals(value)) {
                return true;
            }
        }

        return false;
    }

}
